package com.kly.cashmall.base;

import android.Manifest;
import android.content.Context;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.kly.cashmall.BuildConfig;
import com.kly.cashmall.services.Params;
import com.kly.cashmall.services.UserInfoHelper;
import com.kly.cashmall.utils.function.CommonUtils;
import com.kly.cashmall.utils.data.MD5;
import com.kly.cashmall.utils.NetStateUtil;
import com.kly.cashmall.utils.data.ObjectUtils;
import com.kly.cashmall.utils.function.PackageInfoUtil;
import com.kly.cashmall.utils.system.PermissionUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

/**
 * @author zxp
 * @since 27/10/21
 */
public class ParamsBuilder {

    public static class ParamsHelper {

        public String toJsonString(Params params) {

            HashMap<String, Object> formMap = params.getFormMap();
            JsonObject json = new JsonObject();
            checkFormMap(formMap);
            Iterator var2 = formMap.entrySet().iterator();

            while (var2.hasNext()) {
                Map.Entry<String, Object> entry = (Map.Entry) var2.next();
                if (paramsEntrySafe(entry)) {
                    String key = (String) entry.getKey();
                    Object value = entry.getValue();
                    if (value instanceof JsonElement) {
                        json.add(key, (JsonElement) value);
                    } else if (value instanceof Number) {
                        json.addProperty(key, (Number) value);
                    } else if (value instanceof Boolean) {
                        json.addProperty(key, (Boolean) value);
                    } else if (value instanceof Character) {
                        json.addProperty(key, (Character) value);
                    } else {
                        json.addProperty(key, String.valueOf(value));
                    }
                }
            }

            return json.toString();
        }

        protected boolean paramsEntrySafe(Map.Entry<String, Object> entry) {
            return entry != null && !TextUtils.isEmpty((CharSequence) entry.getKey()) && entry.getValue() != null && !TextUtils
                    .isEmpty(entry.getValue().toString());
        }

        private void checkFormMap(Map<String, Object> formMap) {
            if (formMap != null) {
                Iterator var2 = formMap.entrySet().iterator();

                while (var2.hasNext()) {
                    Map.Entry<String, Object> entry = (Map.Entry) var2.next();
                    if (entry.getValue() instanceof JSONArray) {
                        formMap.put(entry.getKey(), ObjectUtils.toJsonArray((JSONArray) entry.getValue()));
                    } else if (entry.getValue() instanceof JSONObject) {
                        formMap.put(entry.getKey(), ObjectUtils.toJsonObject((JSONObject) entry.getValue()));
                    }
                }

            }
        }
    }

    public static String create(Params params, Context context) {
        if (params == null) {
            params = new Params();
        }
        params.setContentType(Params.JSON);
        String postJson = paramsToString(params);
        String localAppKey = HttpConst.getAppKey();//BuildConfig.APP_KEY;
        String localAppVersion = PackageInfoUtil.getVersionName(context);
        String localAppClient = "android";
        String localOpenId = UUID.randomUUID().toString();

        String localFrom = "cashzone";
        String localTimeStamp = String.valueOf(System.currentTimeMillis());
        String localNet = NetStateUtil.getConnectedType(context);
        int localVersionCode = PackageInfoUtil.getVersionCode(context);
//        String localClientId = BaseSharedDataUtil.getClientId(context);
        String deviceId="";
        if (!PermissionUtils.lacksPermission(context, Manifest.permission.READ_PHONE_STATE)) {
            deviceId = CommonUtils.getDeviceId(context);
        }


        StringBuilder basicParams = new StringBuilder();

        basicParams.append(localAppKey);
        basicParams.append(localAppVersion);
        basicParams.append(localAppClient);
        basicParams.append(localVersionCode);
        basicParams.append(localTimeStamp);

        String localChannel = "cashzone";
        String guestId = "";
//        if (!TextUtils.isEmpty(BaseSharedDataUtil.getGuestId(context))) {
//            guestId = BaseSharedDataUtil.getGuestId(context);
//        }
        basicParams.append(guestId);

        String localToken = "";
        if (!TextUtils.isEmpty(UserInfoHelper.getInstance().getToken())) {
            localToken = UserInfoHelper.getInstance().getToken();
            basicParams.append(localToken);
        }

        String localAppSign = MD5.GetMD5Code(MD5.GetMD5Code(basicParams.append(HttpConst.getAppSecret()).toString()));

        String appCode = "39";
        String categoryCode = "cashZoneAll";

        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put(RequestHeaderField.APP_KEY, localAppKey);
            jsonObject.put(RequestHeaderField.APP_VERSION, localAppVersion);
            jsonObject.put(RequestHeaderField.CHANNEL, localChannel);
            jsonObject.put(RequestHeaderField.APP_CLIENT, localAppClient);
            jsonObject.put(RequestHeaderField.OPENID, localOpenId);
            jsonObject.put(RequestHeaderField.FROM, localFrom);
//            jsonObject.put(RequestHeaderField.CLIENT_ID, localClientId);
            jsonObject.put(RequestHeaderField.APP_SIGN, localAppSign);
            jsonObject.put(RequestHeaderField.TIMESTAMP, localTimeStamp);
            jsonObject.put(RequestHeaderField.NET, localNet);
            jsonObject.put(RequestHeaderField.VERSION_CODE, localVersionCode);
            jsonObject.put(RequestHeaderField.TOKEN, localToken);
            jsonObject.put(RequestHeaderField.PACKAGE_NAME, BuildConfig.APPLICATION_ID);
            jsonObject.put(RequestHeaderField.GUEST_ID, guestId);
            jsonObject.put(RequestHeaderField.APP_CODE, appCode);
            jsonObject.put(RequestHeaderField.CATEGORY_CODE, categoryCode);
//            jsonObject.put(RequestHeaderField.APPSFLYER_ID, appsFlyerId);
            jsonObject.put(RequestHeaderField.MOBILE_IMEI, deviceId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return jsonObject.toString();
    }

    public static Params build(@Nullable Params params) {
        if (params == null) {
            params = new Params();
            params.setContentType(Params.JSON);
            return params;
        }
        params.setContentType(Params.JSON);
        return params;
    }


    /**
     * @param params
     * @return
     */
    private static String paramsToString(Params params) {
        String paramsStr = null;
        if (params != null) {
            paramsStr = params.getFormJson();
            if (TextUtils.isEmpty(paramsStr)
                    && params.getFormMap() != null
                    && params.getFormMap().size() > 0) {
                paramsStr = new GsonBuilder().create().toJson(params.getFormMap());
            }
        }
        return paramsStr == null ? "" : paramsStr;
    }
}
